import { create } from "zustand";
import type { StateCreator } from "zustand";
import { immer } from "zustand/middleware/immer";
import {
  devtools,
  persist,
  subscribeWithSelector,
  createJSONStorage,
} from "zustand/middleware";
import { createSelectors } from "@/utils/createSelectors";

/** ---------------state start--------------- */
const initState = {
  cats: {
    bigCats: 0,
    smallCats: 0,
  },
};
/** ---------------state end--------------- */

/** ---------------方法start--------------- */

export const increaseBigCats = () => {
  useTemplateStore.setState((state) => ({
    cats: {
      ...state.cats,
      bigCats: state.cats.bigCats + 1,
    },
  }));
};

export const increaseSmallCats = () => {
  useTemplateStore.setState((state) => {
    // immer用法
    state.cats.smallCats++;
  });
};

export const summary = () => {
  const total =
    useTemplateStore.getState().cats.bigCats +
    useTemplateStore.getState().cats.smallCats;
  return total;
};

/** ---------------方法end--------------- */

const createTemplateSlice: StateCreator<
  typeof initState,
  [
    ["zustand/immer", never],
    ["zustand/devtools", unknown],
    ["zustand/subscribeWithSelector", never],
    ["zustand/persist", unknown]
  ]
> = () => initState;

export const useTemplateStore = createSelectors(
  create<typeof initState>()(
    immer(
      devtools(
        subscribeWithSelector(
          persist(createTemplateSlice, {
            // 存储名称(必须唯一)
            name: "catStore",
            // 自定义存储(默认localStorage)
            storage: createJSONStorage(() => localStorage),
            // 只存储某个字段
            // partialize: (state) => ({ bears: state.bears, color: state.color }),
            // 不存储某个字段
            // partialize: (state) =>
            //   Object.fromEntries(
            //     Object.entries(state).filter(([key]) => !["color"].includes(key))
            //   ),
          })
        ),
        {
          enabled: true, // 是否启用devtools
          name: "CatStore", // devtools名称
        }
      )
    )
  )
);
